<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;

use Storage;

use Session;

class Goodcontroller extends Controller
{
    //商品首页
    public function index(Request $request){
    	$data=DB::table('goods')
    	-> where('good_name','like','%'.$request -> input('keyword').'%')
    	-> paginate($request -> input('pages',5));

    	 foreach($data as $k => $v){
    	 	$dat=DB::table('goods_cate')
    		-> where('id',$v -> cid) -> first();
    		// dd($dat);
    		$data[$k] -> cid = $dat -> cate_name;
    	 }

    	 foreach($data as $k => $v){
    	 	// 为所有商品图片添加路径
    	 	// dd($v);
    	 	$data[$k] -> good_img = "/upload/".$v -> good_img;
    	 	// var_dump($data[$k] -> good_img);
    	 }


    	return view('admin/goods/index',['data' => $data,'request' => $request -> all()]);
    }

    public function preAdd(Request $request){
    	$data=DB::table('goods_cate')
    	-> select('*',DB::raw("CONCAT(cate_path,id) AS sortPath"))
    	-> where('cate_name','like','%'.$request -> input('keyword').'%')
    	->orderby('sortPath')
    	-> paginate($request -> input('pages',5));

    	$alldata =DB::select('select * from goods_cate');

    	$pids = array();

    	foreach ($alldata as $k => $v) {
    		$pids[] = $v ->cate_pid;
    	}
    	$pids =array_unique($pids);
    	// dd($pids);
    	 foreach($data as $k =>$v){
    	 	// 计算 cate_path 的逗号个数
    	 	$num =substr_count($v -> cate_path,',');

    	 	$data[$k] -> cate_name =str_repeat('&nbsp; &nbsp;', $num).'|--'.$v -> cate_name;

    	 	if( in_array($v -> id, $pids)){
    	 		$data[$k] -> enable='0';
    	 	}else{
    	 		$data[$k] -> enable='1';
    	 	}
    	 }

    	 // dd($data);
    	return view('admin.goods.preAdd',['data' => $data,'request' => $request -> all()]);
    }

    public function add($id){
    	$data=DB::table('goods_cate') -> where('id' , $id) ->first();
    	$goods_attrs_id = $data -> goods_attrs_id;
    	// dd($data);
    	$attrs= explode(',', $goods_attrs_id);

    	$cate_name= $data ->cate_name ;

    	$i =0 ;
    	
    	$attrs_arr=array();
    	foreach ($attrs as $k => $v) {
    		$attr_name=DB::table('goods_attr') -> where('id' , $v) ->first();
    		$attrs_arr["$v"] = $attr_name -> attr_name ;
    	}
    	// dd($attrs_arr);
		return view('admin/goods/add',['data' => $data , 'attrs_arr' => $attrs_arr,'i' => $i ,'cate_name' => $cate_name ]);
    }

    public function insert(Request $request){
    	// dd($request -> all());
    	$data =$request -> all() ;
    	$goods =array(
    		'cid' =>$data['cid'],
    		'good_name' =>$data['good_name'],
    		'good_price' =>$data['good_price'],
    		'good_store' =>$data['good_store'],
    		'good_status' =>$data['good_status'],
    		'good_detail' =>$data['good_detail'],
    		'good_desc' =>$data['good_desc']
    		);
    	// dd($goods);
    	// 文件上传
    	if($request->hasFile('good_img')){
    		if ($request->file('good_img') ->isValid()){
    			// 获取文件的后缀名
    			$suffix = $request->file('good_img') -> getClientOriginalExtension();
    			// 设置文件的名称
    			$fileName = time().mt_rand(0,99999).'.'.$suffix;
	    		$request->file('good_img')->move('./upload/', $fileName);
	    	}
    	}

    	// dd($fileName);
    	$goods['good_img'] = $fileName ;
    	$attr_value =$request ->except('_token','cid','good_name','good_price','good_store','good_status','good_detail','good_img','good_desc');
    	// dd($attr_value);

    	$attr_id ='';

    	foreach($attr_value as $k => $v){
    		$res = DB::table('goods_value') -> where('attr_value' ,$v ) -> first();
    		// dd($res);
    		if($res){
    			$id = $res -> id;
    			$attr_value[$k] = $id ;
    		}else{
    			$id = DB::table('goods_value') ->insertGetId(['attr_value' => $v]);
    			$attr_value[$k] = $id ;
    		}
    	}

    	// dd($attr_value);

    	foreach($attr_value as $k => $v){
    		
    		$res =DB::select('select * from goods_attr_val where attr_name_id = ? and attr_value_id', [$k,$v]);
    		if($res){
    			$id = $res['id'];
    			$attr_id .=$id.',';
    		}else{
    			$id = DB::table('goods_attr_val') ->insertGetId(['attr_name_id' => $k , 'attr_value_id' => $v]);
    			$attr_id .=$id.',';
    		}
    	}

    	// dd($attr_id);
    	$goods['attr_id'] = $attr_id;

    	$res =DB::table('goods') ->insert($goods);

    	if ($res) {
    		return redirect('/admin/goods');
    	}else{
    		return back()->with(['info' => '数据添加失败']);
    	}
    }

    public function ajaxUpdateData(Request $request){
    	// return '1111';
    	// dd($request -> all());
    	
		$res = DB::table('goods') -> where('id',$request -> input('id')) -> update([$request -> input('attr_name') => $request -> input('attr_value')]);
    	if($res){
    		return response() -> json(1);
    	}else{
    		return response() -> json(0);
    	}
    }

    public function ajaxUpdateStatus(Request $request){
    	// dd($request -> all());
    	$res = DB::table('goods') -> where('id',$request -> input('id')) -> update(['good_status' => $request -> input('good_status')]);
    	if($res){
    		return response() -> json(1);
    	}else{
    		return response() -> json(0);
    	}
    }

    public function edit($id){
    	$data = DB::table('goods') -> where('id',$id) ->first();
    	// dd($data);
    	$attr_id =trim($data -> attr_id,',');
    	$attr_id_arr = explode(',', $attr_id);
    	$i=0;
    	// dd($attr_id_arr);
    	$attrs_arr = array();
    	foreach($attr_id_arr as $k => $v){
    		$dat = DB::table('goods_attr_val') -> where('id',$v) ->first();
    		// dd($dat);
    		$key = DB::table('goods_attr') ->where('id' , $dat ->attr_name_id) ->first() ->attr_name;
    		$value = DB::table('goods_value') ->where('id' , $dat ->attr_value_id) ->first() ->attr_value;

    		// dd($key);

    		$attrs_arr[$key] = $value;
    	}

    	// dd($attrs_arr);
    	return view('admin/goods/edit',['data' => $data , 'attrs_arr' => $attrs_arr,'i' => $i ]);
    }

    public function doedit(Request $request){
    	// dd($request -> all());
    	$data =$request -> all();

    	$id1 = $data['id'];
    	// dd($id);
    	$goods =array(
    		'good_name' =>$data['good_name'],
    		'good_price' =>$data['good_price'],
    		'good_store' =>$data['good_store'],
    		'good_status' =>$data['good_status'],
    		'good_detail' =>$data['good_detail'],
    		'good_desc' =>$data['good_desc'],
    		);

    	$oldFileName ='./upload/'.$data['img'];
    	// dd($oldFileName);
    	// dd($goods);
    	// 文件上传
    	if($request->hasFile('good_img')){
    		if ($request->file('good_img') ->isValid()){
    			// 获取文件的后缀名
    			$suffix = $request->file('good_img') -> getClientOriginalExtension();
    			// 设置文件的名称
    			$fileName = time().mt_rand(0,99999).'.'.$suffix;
	    		$request->file('good_img')->move('./upload/', $fileName);

	    		$goods['good_img'] = $fileName ;

	    		Storage::delete($oldFileName);
	    	}
    	}else{
    		$goods['good_img'] = $data['img'] ;
    	}

    	// dd($fileName);
    	
    	$attr_value =$request ->except('_token','id','good_name','good_price','good_store','good_status','good_detail','good_img','img','good_desc');
    	// dd($attr_value);

    	$attr_id ='';
    	// dd($attr_value);
    	// 
    	// 遍历参数
    	foreach($attr_value as $k => $v){
    		// 查找数据的值是否存在
    		$res_value = DB::table('goods_value') -> where('attr_value' ,$v ) -> first();
    		// dd($res);
    		// 如果存在
    		if($res_value){
    			// 将数值的ID存入 $id_value
    			$id_value = $res_value -> id;
    			// 查找数据的键是否存在
    			$res_attr = DB::table('goods_attr') -> where('attr_name' ,$k ) -> first();
	    		// dd($res);
	    		// 加入键存在
	    		if($res_attr){
	    			// 将键对应的ID赋给 $id_attr
	    			$id_attr = $res_attr -> id;
	    		}else{
	    			// 否则的话将键值插入 goods_attr 表中 ,并返回 ID
	    			$id_attr = DB::table('goods_attr') ->insertGetId(['attr_name' => $k]);
	    		}
	    		$attr_value_final[$id_attr] = $id_value ;
    		}else{
    			// 将数值插入 goods_value 中并返回ID
    			$id_value = DB::table('goods_value') ->insertGetId(['attr_value' => $v]);
    			// 查找数值是否存在
    			$res = DB::table('goods_attr') -> where('attr_name' ,$k ) -> first();
	    		// dd($res);
	    		if($res){
	    			// 存在的话 赋给 $id_attr
	    			$id_attr = $res -> id;
	    		}else{
	    			// 否则的话将键值插入 goods_attr 表中 ,并返回 ID
	    			$id_attr = DB::table('goods_attr') ->insertGetId(['attr_name' => $k]);
	    		}

	    		$attr_value_final[$id_attr] = $id_value ;
    		}
    	}


    	// dd($attr_value_final);

    	foreach($attr_value_final as $k => $v){
    		
    		// $res =DB::select('select * from goods_attr_val where attr_name_id = ? and attr_value_id = ? ', [$k,$v]);
    		$res = DB::table('goods_attr_val') ->where('attr_name_id',$k) -> where('attr_value_id',$v) -> first();
    		if($res){
    			// dd($res);
    			$id = $res -> id;
    			$attr_id .=$id.',';
    		}else{
    			$id = DB::table('goods_attr_val') ->insertGetId(['attr_name_id' => $k , 'attr_value_id' => $v]);
    			$attr_id .=$id.',';
    		}
    	}

    	// dd($attr_id);
    	$goods['attr_id'] = $attr_id;
    	// dd($id1);
    	// dd($goods);
    	$res =DB::table('goods') ->where('id', $id1) ->update($goods);
    	// dd($res);
    	if ($res) {
    		return redirect('/admin/goods');
    	}else{
    		return back()->with(['info' => '数据添加失败']);
    	}
    }

    public function delete($id){
        $res = DB::table('goods') -> where('id',$id) -> delete();

        if($res){
            return redirect('/admin/goods');
        }else{
            return back()->with(['info' => '数据删除失败']);
        }
    }


    public function goodedit($id){
        // return $id;
        $data = DB::table('good_detail') -> where('good_id',$id) ->get();
        $good_id = $id;
        // dd($data);
        $display = '0';
        $result= 'none';
        return view('admin/goods/goodedit',['data' => $data ,'good_id' => $good_id , 'result' => $result ,'display' => $display ]);
    }

    public function updateDetail(Request $request){
        // dd($request -> all());
        $data = $request ->all();
        $good_detail['good_id'] = $data['good_id'];
        $good_detail['good_color'] = $data['good_color'];
        $good_detail['good_net_type'] = $data['good_net_type'];
        $good_detail['good_ROM'] = $data['good_ROM'];
        $good_detail['good_store'] = $data['good_store'];
        $good_detail['good_price'] = $data['good_price'];

        $good_id = $data['good_id'];
        // 文件上传
        if($request->hasFile('good_img')){
            if ($request->file('good_img') ->isValid()){
                // 获取文件的后缀名
                $suffix = $request->file('good_img') -> getClientOriginalExtension();
                // 设置文件的名称
                $fileName = time().mt_rand(0,99999).'.'.$suffix;
                $request->file('good_img')->move('./upload/', $fileName);
                $good_detail['good_img'] = $fileName;
            }
        }
        // dd($good_detail);
        $res_insert = DB::table('good_detail') -> insert($good_detail);

        if ($res_insert) {
            $result = '1';
        }else{
           $result = '0'; 
        }
        
        $display = '1';
        $data = DB::table('good_detail') ->where('good_id',$good_id) ->get();

        return back();
    }


    public function ajaxUpdateDetail(Request $request){
        // return '1111';
        // dd($request -> all());
        
        $res = DB::table('good_detail') -> where('id',$request -> input('id')) -> update([$request -> input('attr_name') => $request -> input('attr_value')]);
        if($res){
            return response() -> json(1);
        }else{
            return response() -> json(0);
        }
    }


    public function deleteDetail($id){
        $res = DB::table('good_detail') -> where('id',$id) -> delete();

        if($res){
            return back()->with(['info' => '数据删除成功']);
        }else{
            return back()->with(['info' => '数据删除失败']);
        }
    }

    public function editDetail($id,$good_id){
        // return $id;
        $data = DB::table('good_detail') -> where('id',$id) ->first();
        $good_id = $id;
        return view('admin/goods/editDetail',['data' => $data ,'good_id' => $good_id ]);
    }


    public function doeditDetail(Request $request){
        // dd($request -> all());
        $data =$request -> all();

        $id = $data['id'];
        $good_id = $data['good_id'];
        // dd($id);
        $good_Detail =array(
            'good_id' =>$data['good_id'],
            'good_color' =>$data['good_color'],
            'good_store' =>$data['good_store'],
            'good_ROM' =>$data['good_ROM'],
            'good_net_type' =>$data['good_net_type'],
            'good_price' =>$data['good_price'],
            );

        $oldFileName ='./upload/'.$data['img'];
        // dd($oldFileName);
        // dd($goods);
        // 文件上传
        if($request->hasFile('good_img')){
            if ($request->file('good_img') ->isValid()){
                // 获取文件的后缀名
                $suffix = $request->file('good_img') -> getClientOriginalExtension();
                // 设置文件的名称
                $fileName = time().mt_rand(0,99999).'.'.$suffix;
                $request->file('good_img')->move('./upload/', $fileName);

                $good_Detail['good_img'] = $fileName ;

                Storage::delete($oldFileName);
            }
        }else{
            $good_Detail['good_img'] = $data['img'] ;
        }

        // dd($fileName);
        
        // dd($good_Detail);
        $res =DB::table('good_detail') ->where('id', $id) ->update($good_Detail);
        // dd($res);
        if ($res) {
            return redirect("admin/goods/goodedit/{$good_id}");
        }else{
            return back()->with(['info' => '数据添加失败']);
        }
    }
}
